package com.zch.starter.metrics.prometheus.springboot.starter.config.auto;


import com.zch.starter.metrics.prometheus.springboot.starter.config.properties.PrometheusActuatorProperties;
import com.zch.starter.metrics.prometheus.springboot.starter.metrics.ExportMetricsService;
import com.zch.starter.metrics.prometheus.springboot.starter.metrics.RegisterGaugeServer;
import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.autoconfigure.metrics.MeterRegistryCustomizer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;


/**
 * ConditionalOnProperty条件满足-》MetricsAutoConfiguration交给spring 管理创建-》@PropertySource生效-》MeterRegistry
 * 被spring自动创建-》下面的@Bean 方法都生效
 * ConditionalOnProperty 注解使得prometheus.autoconfigure.enable=true 时，该注解作用的MetricsAutoConfiguration类 才会交给spring管理
 * 也才会执行下面的@Bean 方法
 */
//@Configuration //由于在spring.factories 中org.springframework.boot.autoconfigure
// .EnableAutoConfiguration配置了该类，已经交给spring了，该注解可以去掉了
// 判断prometheus.autoconfigure.enabled的值是否为“true”， matchIfMissing = false：,只在true 时才加载
@ConditionalOnProperty(prefix = "prometheus.autoconfigure", name = "enabled", havingValue = "true", matchIfMissing = false)
@EnableConfigurationProperties(value = {PrometheusActuatorProperties.class})
@PropertySource(value = {"classpath:actuator-management.properties"})
public class MetricsAutoConfiguration {


    @Bean("exportMetricsService")
    @ConditionalOnMissingBean // 表示只创建一个bean
    ExportMetricsService metricsService(MeterRegistry registry) {
        ExportMetricsService exportMetricsService = new ExportMetricsService();
        exportMetricsService.setRegistry(registry);
        return exportMetricsService;
    }


    @Bean("registerGaugeServer")
    @ConditionalOnMissingBean // 表示只创建一个bean
    RegisterGaugeServer registerGaugeServer (MeterRegistry registry) {
        RegisterGaugeServer registerGaugeServer = new RegisterGaugeServer();
        registerGaugeServer.setMeterRegistry(registry);
        return registerGaugeServer;
    }


    /**
     * 给 MeterRegistry bean 初始化一些通用tags
     * @param applicationName 防止有的应用没有配置该值 弄个默认值
     * @return
     */
    @Bean
    @ConditionalOnMissingBean // 表示只创建一个bean
    MeterRegistryCustomizer<MeterRegistry> configurer(@Value("${spring.application.name:DEFAULT}") String applicationName) {
        return (registry) -> {
            registry.config().commonTags("application", applicationName);
        };
    }


}
